'use strict'

const router = require('logoran-joi-router');
const utilJson = require('util-json');
const Joi = require('joi');
const Enjoi = require('xy-enjoi');
const routers = new router();
const path = require('path');
const fs = require('fs');
const assert = require('assert');

module.exports = function(api,app,currentPath,routerConfig){
  // var controllers = routerConfig.controllers;   //控制器由原来的路由文件提取到了handlers中，所有目前这里不需要使用
  const handlers = routerConfig.handlers;       //handlers

  var befores = {};//存放路由的berfor
  var reqs = {};  //存放路由的规则
  var Xpath = []; //缓存路由上下级
  var routerObj = {}; //解析后的路由对象

  //路由加载
  var paths = api.paths;
  loadCommonPath(paths);
  /**
   * 解析并加载路由规则
   * @param {paths} 路由配置
   */
  function loadCommonPath(paths){
    for(var key in paths){
      //深度遍历路由树
      parserPath(paths[key],key);
      Xpath.pop();
    }
    // console.log(reqs['/orders']);
    addRouterObj(reqs);
    // console.log(routers.middleware());
  }

  /**
   * 解析路由树
   * @param {obj} 顶层路由对象
   * @param {key} 顶层路由键
   */
  function parserPath(obj,key){
    let lastPath = key;
    if(key.match('{.*}')){
      lastPath = key.replace('{',':');
      lastPath = lastPath.replace('}','');
    }
    Xpath.push(lastPath);
    //检查是否有before
    if(obj['x-before']){
      befores[key] = obj['x-before'];
    }
    //检查是否含有路由
    if(obj['x-paths']){
      for(var key1 in obj['x-paths']){
        parserPath(obj['x-paths'][key1],key1);
        Xpath.pop();
      }
    }else{//如果没有下级路由 则返回
      //一个路径可能有多个请求，遍历
      // console.log("\r\n\r\n",obj,Xpath,key);
      let subRouter = {
        path:key,
        list:[]
      };
      for(let k in obj){
        let list = {
          method:k,
          handler:obj[k]['x-handler'],
          parameters:obj[k].parameters,
          requestBody:obj[k].requestBody,
          response:obj[k].responses,
        };
        subRouter.list.push(list);
      }
      if(!reqs[Xpath[0]]){
        reqs[Xpath[0]] = [];
      }
      reqs[Xpath[0]].push(subRouter);
    }
  }

  //将路由对象添加到路由中
  function addRouterObj(reqs){
    //测试路由
    routers.use("/xiaoyao",
      router()
      .route({
          path: '/test',
          method: 'get',
          handler: [(ctx,next)=>{
            ctx.body = "hello i am is xiaoyao/test";
          }],
          validate: {
              params: {
                  // id: Joi.number().integer().required() //用户编号
              },
              output: {
                  200: {
                    body: Joi.string().required()
                  }
              }
          }
      }).middleware());

    var handlerTest = function(path){
      return async (ctx,next) => {
        console.log("hello I am is ",path);
        ctx.body = "hello I am is "+path;
      }
    }
    //路由模型
    function routerTmp (){
      return {
        path:"",
        method:"",
        handler:[],
        validate:{
          params:{},
          query:{}
        }
      }
    }
    //参数模型
    function parametersTmp (){
      return {
          "type": "object",
          "required": [],
          "properties": {
          }
      }
    }

    for(let key in reqs){
      var mainPath = key;         //主路径
      const route = new router();
      let pathLen = reqs[key].length;
      for(var i = 0; i <= pathLen-1; i++){
        let list = reqs[key][i].list;
        let methodLen = list.length;
        var path = reqs[key][i].path;
        for(var j = 0; j <= methodLen-1; j++){
          var tmp = new routerTmp();
          tmp.path = path;
          tmp.method = list[j].method.split(",");
          // tmp.handler = [handlerTest(mainPath+path)];//目前为测试handler
          let handler = list[j].handler;
          // console.log(handler);
          if(handler.length > 0){
            if(handler.indexOf("(") >= 0 && handler.indexOf(")") >=0 ){
              handler = eval(handler)
            }else{
              handler = eval(handler+"()");
            }
          }else{
            handler = handlerTest;
          }

          tmp.handler = handler;
          //逐个分析参数是params还是query,并转成joi
          if(list[j].parameters){
            let params = new parametersTmp();
            let query = new parametersTmp();
            let parameters = list[j].parameters;
            let paramsLen = parameters.length;
            for(let k = 0;k <= paramsLen-1; k++){
              let name = parameters[k]["name"];
              let schema = parameters[k]['schema'];
              switch (parameters[k]['in']) {
                case "path":
                  params.properties[name] = schema;
                  parameters[k]['required']?params.required.push(name):"";
                  break;
                case "query":
                  query.properties[name] = schema;
                  parameters[k]['required']?query.required.push(name):"";
                  break;
                default:break;
              }

            }
            tmp.validate.params = Enjoi(params);
            tmp.validate.query = Enjoi(query);
          }
          //将body转成joi
          if(list[j].requestBody && list[j].requestBody.content){
            let bodyResult = utilJson.findObjectByKey("schema",list[j].requestBody);
            let typeResult = Object.keys(list[j].requestBody.content)[0];
            if(bodyResult){
              tmp.validate.body = Enjoi(bodyResult);
              tmp.validate.type = typeResult.split("/")[1];
            }
          }
          //将ouput转成joi
          if(list[j].response && list[j].response['200']){
            //涉及到orders的暂时返回验证为空
            if(mainPath == "/orders"){
              tmp.validate.output = {};
            }else{
              list[j].response["200"].body = Enjoi(list[j].response["200"].schema);
              tmp.validate.output = {};
              tmp.validate.output["200"] = list[j].response["200"];
            }
          }
          // console.log(tmp);
          route.route(tmp);
        }
      }
      routers.use(mainPath,route.middleware());
    }
    app.use(routers.middleware());
  }
}
